package com.rongke.web.ajaxUtil;


import net.sf.json.JSONObject;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by bilibili on 2017/10/23.
 */
public class AjaxUtil {



    /**
     * 判断是否是ajax请求
     * @param request
     * @param response
     * @return
     */
    public  static boolean  isAjaxRequest(HttpServletRequest request, HttpServletResponse response) {
        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * response 输出JSON
     * @param response
     * @param resultMap
     * @throws Exception
     */
    public static void out(ServletResponse response, Map<String, String> resultMap){

        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            out.println(JSONObject.fromObject(resultMap).toString());
        } catch (Exception e) {
           e.printStackTrace();
        }finally{
            if(null != out){
                out.flush();
                out.close();
            }
        }
    }


    /**
     * response 跨域请求 输出JSON
     * @param response
     * @param resultMap
     * @param crossDomain  是否跨域
     * @throws Exception
     */
    public static void out(HttpServletResponse response, Map<String, String> resultMap,Boolean crossDomain,HttpServletRequest request){
        PrintWriter out = null;
        response.setContentType("text/plain");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setDateHeader("Expires", 0);
        if(crossDomain){
            try {
                out = response.getWriter();
                JSONObject resultJSON = JSONObject.fromObject(resultMap); // 根据需要拼装json
                String jsonpCallback = request.getParameter("jsonpCallback");// 客户端请求参数
                out.println(jsonpCallback + "(" + resultJSON.toString(1, 1) + ")");// 返回jsonp格式数据
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


}
